<?php

namespace app\index\controller;

use app\admin\model\Category;
use think\Controller;
use think\Request;

class Listpage extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //接受cid参数
        $cate_id = input('param.cate_id');
        $price = input('param.price');
        //dump($price);
        $data = db('category')->select();
        //1.面包屑导航
        $fatherData = $this->getFather($cate_id,$data);
        //数组翻转
        $fatherData = array_reverse($fatherData);
        $this->assign('fatherData',$fatherData);
        //2.根据参数处理数据
        $goodsData = $this->loadData($cate_id,$data,$price);
        $this->assign('goodsData',$goodsData);
        return view();
    }

    /**
     *加载列表页数据
     */
    protected function loadData($cate_id,$data,$price)
    {
        //1.获取当前cid所有子集数据，包含自己
        $cids = (new Category())->getSon($cate_id,$data);//调用category模型中找子集方法
        $cids[] = $cate_id;//把自己追加进去
        if($price=='desc'){
            $goodsData = db('details')->whereIn('pid',$cids)->order('now_price desc')->select();
        }else{
            $goodsData = db('details')->whereIn('pid',$cids)->order('now_price asc')->select();
        }
        return $goodsData;
    }




    /**
     * 递归找父级数据
     * @param $cid		当前栏目cid
     * @param $data		所有栏目数据
     *
     * @return array	所有父级数据包含自己
     */
    protected function getFather( $cate_id, $data)
    {
        static $temp = [];
        foreach($data as $k=>$v){
            if($v['cate_id'] == $cate_id){
                $temp[] = $v;
                $this->getFather($v['pid'],$data);
            }
        }
        return $temp;
    }



}
